<template>
  <div class="finance_box" ref="myElementRef">
    <div ref="searchBox" v-if="state.flng">
      <hc-search :data="serchData" @serch="getSarch($event)" @getadd="getadd($event)" />
    </div>
    <!-- 表格 -->
    <div class="table_box">
      <hc-table :tableData="tableData" :column="state.tableHeader" :offsetHeight="state.offsetHeight">
        <template #avatar_url="{ row }">
          <div v-if="row.avatar_url">
            <el-avatar :size="50" :src="row.avatar_url" />
          </div>
        </template>
        <template #sex="{ row }">
          {{ row.sex == 1 ? '男' : row.sex == 2 ? '女' : '未知' }}
        </template>
        <template #roleList="{ row }">
          <div v-if="row.roleList">
              <el-tag type="primary" v-for="(itme,index) in row.roleList" :key="index">{{itme.role_name}}</el-tag>
          </div>
        </template>
        <template #status="{ row }">
          {{ row.status == 1 ? '正常' : '禁止' }}
        </template>
        <template #operation="scope">
          <div class="btn_box_det">
            <el-button size="small" type="text" @click="edit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" link @click="del(scope.row)">删除</el-button>
          </div>
        </template>
      </hc-table>
    </div>
    <el-dialog align-center v-model="dialogVisible" title="人员信息" width="800" draggable>
      <div class="userAdd_man">
        <el-form label-width="auto" :model="formLabelAlign" class="userFrom" ref="formRef" :rules="rules">
          <el-form-item label="用户账号" prop="username" v-if="formLabelAlign.user_id>0">
            <el-input v-model="formLabelAlign.username" placeholder="请输入" :disabled="true"/>
          </el-form-item>
          <el-form-item label="用户账号" prop="username" v-else>
            <el-input v-model="formLabelAlign.username" placeholder="请输入"  />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="formLabelAlign.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="formLabelAlign.sex" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker style="flex: 1" value-format="YYYY-MM-DD" v-model="formLabelAlign.birth_date" type="date"
              placeholder="选择生日" />
          </el-form-item>

          <el-form-item label="手机">
            <el-input v-model="formLabelAlign.phone" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="邮箱">
            <el-input v-model="formLabelAlign.email" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="部门">
            <el-select v-model="formLabelAlign.department_id" placeholder="请选择">
              <el-option v-for="item in Departments" :key="item.department_id" :label="item.department_name"
                :value="item.department_id" />
            </el-select>
          </el-form-item>
          <el-form-item label="职位">
            <el-input v-model="formLabelAlign.position" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="入职日期">
            <el-date-picker style="flex: 1" value-format="YYYY-MM-DD" v-model="formLabelAlign.hire_date" type="date"
              placeholder="选择日期" />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="formLabelAlign.user_roles" placeholder="请选择" filterable multiple>
              <el-option v-for="item in RoleData" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
            </el-select>
          </el-form-item>
          <el-form-item label="账户状态">
            <el-select v-model="formLabelAlign.status" placeholder="请选择">
              <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>


        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="subimt($refs.formRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import hcSearch from "@/components/hc-search/index.vue";
import hcTable from "@/components/hc-table/index.vue";
import { onMounted, reactive, ref, nextTick, onUnmounted, onActivated } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { RolesPullDown } from '@/api/system.js';
import { DepartmentsPullDown } from '@/api/departments.js';
import { UsersAdd,UsersList,UsersDel } from '@/api/user.js';
const myElementRef = ref();
const searchBox = ref();
let page = ref(1);
let limit = ref(20);
let maxPage = ref(0);
const dialogVisible = ref(false);
const rules = reactive({
  username: [
    {
      required: true,
      message: "账号不能为空",
      trigger: "blur",
    },
  ],
});
const options = [
  { label: "女", value: 2 },
  { label: "男", value: 1 },
];
const options1 = [
  { label: "禁止", value: 0 },
  { label: "正常", value: 1 },
];
const RoleData = ref([]);
const Departments = ref([]);

const tableData = ref([]);

const serchData = reactive([
  {
    label: "姓名",
    type: "input",
    value: "",
  },

  {
    label: "",
    type: "add",
    value: true
  }
]);

const state = reactive({
  title: "",
  column: [
    {
      type: "index",
      show: true,
      label: "序号",
      width: 80,
    },
    {
      prop: "avatar_url",
      show: true,
      label: "头像",
      width: 80,
    },
    {
      prop: "username",
      show: true,
      label: "账号",
      width: 100,
    },
    {
      prop: "name",
      show: true,
      label: "姓名",
      width: 100,
    },
    {
      prop: "sex",
      show: true,
      label: "性别",
      width: 80,
    },
    
    {
      prop: "email",
      show: true,
      label: "邮箱",
      width: 120,
    },
    
    {
      prop: "phone",
      show: true,
      label: "手机号",
      width: 120,
    },
    
    {
      prop: "birth_date",
      show: true,
      label: "出生日期",
      width: 120,
    },
    
    {
      prop: "department_name",
      show: true,
      label: "所属部门",
      width: 120,
    },
    {
      prop: "position",
      show: true,
      label: "职位",
      width: 120,
    },
    
    {
      prop: "hire_date",
      show: true,
      label: "入职日期",
      width: 120,
    },
    {
      prop: "roleList",
      show: true,
      label: "角色",
      width: 140,
    },
    
    {
      prop: "status",
      show: true,
      label: "账户状态",
      width: 120,
    },
    
    {
      prop: "last_login_ip",
      show: true,
      label: "最后登录IP",
      width: 160,
    },
    {
      prop: "last_login_time",
      show: true,
      label: "最后登录时间",
      width: 160,
    },
    {
      prop: "created_at",
      show: true,
      label: "创建时间",
      width: 160,
    },
    {
      prop: "operation",
      show: true,
      label: "操作",
      width: 140, 
    },
  ],
  flng: true,
  offsetHeight: 0,
  tableHeader: [],
});
const formLabelAlign = reactive({
  user_id: 0,
  username: "",
  name: "",
  sex: 1,
  email: "",
  phone: "",
  birth_date: "",
  department_id: "",
  position: "",
  hire_date: "",
  status: 1,
  employee_id: "",
  user_roles: []
});

onMounted(() => {
  try {
    nextTick(() => {
      offHeighths();
    });
    window.onresize = () => {
      nextTick(() => {
        offHeighths();
      });
    };
    tableHeaderFn();
  } catch { }
  getList();
  getRoleList();
  getDepartmentsPullDown();
});
const getRoleList = async (id) => {
  const res = await RolesPullDown({});
  RoleData.value = res.data || [];
  // console.log(RoleData.value)
};
const getDepartmentsPullDown = async (id) => {
  const res = await DepartmentsPullDown({});
  Departments.value = res.data || [];
  // console.log(RoleData.value)
};


// 动态改变表头
const change = (item) => {
  tableHeaderFn();
};

const offHeighths = () => {
  if (myElementRef.value) {
    state.offsetHeight =
      myElementRef.value?.offsetHeight - 130 - searchBox.value?.offsetHeight;
  }
};

onUnmounted(() => {
  window.onresize = null;
});

const getadd = () => {
  // console.log("新增");


  Object.assign(formLabelAlign, {
    user_id: 0,
    username: "",
    name: "",
    sex: 1,
    email: "",
    phone: "",
    birth_date: "",
    department_id: "",
    position: "",
    hire_date: "",
    status: 1,
    employee_id: "",
    user_roles: []

  })
  dialogVisible.value = true
};
const edit = async (row) => {
  Object.assign(formLabelAlign, {
    user_id: row.user_id,
    username: row.username,
    name: row.name,
    sex: row.sex,
    email: row.email,
    phone: row.phone,
    birth_date: row.birth_date,
    department_id: row.department_id,
    position: row.position,
    hire_date: row.hire_date,
    status: row.status,
    employee_id: row.employee_id,
    user_roles: row.checkedKeys

  })
  dialogVisible.value = true
};

// 查询过来的数据
const getSarch = (data) => {
  // console.log("查询", data);
  page.value = 1
  getList()
};


const pageChange = (currentPage) => {
  // console.log(currentPage, "0002")
  page.value = currentPage;
  // getSearch(searchData)
  getList();
}

const limitChange = (currentLimit) => {
  // console.log(currentLimit, "0001")
  page.value = 0;
  limit.value = currentLimit;
  getList();
}

// 表头筛选
const tableHeaderFn = () => {
  state.tableHeader = state.column.filter((v) => {
    if (v.show) {
      return v.show == true;
    } else {
      v.show = false;
    }
  });
};
const getList = async () => {
  // console.log(serchData[0].value)
  const res = await UsersList({
    page: page.value,
    limit: limit.value,
    name: serchData[0].value
  });
  tableData.value = res.data || [];
  maxPage.value = res?.maxPage || 0;
};

const subimt = async (formEl) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const data = { ...formLabelAlign };
        console.log(data)

        const res = await UsersAdd(data);
        if (res.code === 200) {
          dialogVisible.value = false;
          ElMessage.success('保存成功');
        } else {
          ElMessage.error(res.msg || '保存失败');
        }

        getList()

      } catch (error) {
        ElMessage.error('保存失败，请重试');
      } finally {

      }
    } else {
      ElMessage.warning('请填写完整的信息');
    }
  });
};
const del = (row) => {
  ElMessageBox.alert('确认要删除用户信息吗', '删除提醒', {
    confirmButtonText: '确认',
    callback: (action) => {
      if (action == "confirm") {
        // console.log(111)
        getDel(row)
      }

    },
  })
};
const getDel = async (row) => {
  // console.log(serchData[0].value)
  const res = await UsersDel({
    user_id: row.user_id
  });
  if (res.code === 200) {
    // dialogVisible.value = false;
    ElMessage.success('删除成功');
  } else {
    ElMessage.error(res.msg || '删除失败');
  }
  getList()
};
</script>

<style lang="less" scoped>
.finance_box {
  flex: 1;
  overflow: auto;
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  margin-right: 10px;
}

.btn_box {
  height: 40px;
  display: flex;
}

.table_box {
  width: 100%;
}

/deep/.el-button-group .el-button--primary:first-child {
  background-color: #1e6aed;
  border: none;
}

.serBtn {
  margin-left: 10px;
  background-color: #f0f0f0;
  color: #000;
  border: none;
}

.serBtn:hover {
  background-color: #f0f0f0;
  color: #000;
}

.opBtn {
  margin: 0 !important;
}

.opBtn:hover {
  color: #e6a755;
}

.userAdd_man {
  min-height: 360px;
  // max-height: 600px;
  overflow: auto;
  padding: 0 30px;
}

.userFrom {
  display: grid;
  gap: 20px;
  /* 可选，添加网格项之间的间隙 */
  grid-template-columns: repeat(2, 1fr);
}

.el-form-item {
  margin-bottom: 0;
}

.tree_man {
  padding: 0 30px;
}

.tree_box {
  min-height: 300px;
  max-height: 400px;
  overflow: auto;
}

.user_name {
  border: 1px solid #eee;
  margin-top: 10px;
  min-height: 150px;
}
</style>
